package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"liao/api/request"
	"liao/glodal"
	"liao/inits"
	"liao/model"
	"net/http"
	"time"
)

func UserList(context *gin.Context) {
	var user []model.Contact
	glodal.DB.Find(&user)
	marshal, err := json.Marshal(user)
	if err != nil {
		return
	}
	glodal.Rdb.Set(inits.Ctx, "context", marshal, time.Hour*1)
	context.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "查询成功",
		"data": user,
	})
}

func Apply(context *gin.Context) {
	var req request.FriendApply
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数失败",
		})
		return
	}
	apply := model.FriendApply{
		FriendId: req.FriendID,
		UserId:   req.UserID,
		Status:   req.Status,
	}
	glodal.DB.Create(&apply)
	context.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "好友申请已发送",
	})
}

func StatusUp(context *gin.Context) {
	var req request.StatusUp
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数失败",
		})
		return
	}
	err := glodal.DB.Model(&model.FriendApply{}).Where("friend_id = ? and user_id =?", req.FriendID, req.UserID).Update("status", 1)
	if err != nil {
		friend := model.Friend{
			UserId:   req.UserID,
			FriendId: req.FriendID,
		}
		glodal.DB.Create(&friend)
		m := model.Friend{
			UserId:   req.FriendID,
			FriendId: req.UserID,
		}
		glodal.DB.Create(&m)
	}
	context.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "好友添加成功",
	})
}
